package com.black.play.component.base;

import com.black.play.common.FormComponent;

import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ylx
 */
public class AppRadio extends FormComponent<JPanel> {
    private final String[] options;
    private final Map<String, JRadioButton> buttonMap = new HashMap<>();

    public AppRadio(String label, String[] options) {
        this(label, options, options[0]);
    }

    public AppRadio(String label, String[] options, String value) {
        super(label);
        this.options = options;
        this.value = value;
        ButtonGroup group = new ButtonGroup();
        this.constraints.gridx = 1;
        this.constraints.gridy = 0;
        this.constraints.gridwidth = GridBagConstraints.REMAINDER;
        this.component.setLayout(new BoxLayout(component, BoxLayout.X_AXIS));

        for (String option : options) {
            JRadioButton radioButton = new JRadioButton(option);
            if (option.equals(value)) {
                radioButton.setSelected(true);
            }
            group.add(radioButton);
            component.add(radioButton);
            buttonMap.put(option, radioButton);
        }
    }

    @Override
    public void initComponent() {
        this.component = new JPanel();
    }

    @Override
    public String getValue() {
        for (Map.Entry<String, JRadioButton> entry : buttonMap.entrySet()) {
            if (entry.getValue().isSelected()) {
                return entry.getKey();
            }
        }
        return options[0];
    }

    @Override
    public void setText() {
        JRadioButton radioButton = buttonMap.get(value);
        radioButton.setSelected(true);
    }
}
